/*
 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bstefanescu
 */
package org.nuxeo.gwt.habyt.app.client.widgets;

import org.nuxeo.gwt.habyt.templates.client.widgets.HasReplaceElement;

import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * CSS based tab bar from:
 * http://woork.blogspot.com/2008/03/clean-tab-bar-digg-like-using-css.html
 * 
 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
 * 
 */
public class TabBar extends ComplexPanel implements HasReplaceElement {

    public TabBar() {
        super();
        setElement(DOM.createElement("ul"));
        setStyleName("tab");
    }

    public void addTab(ActionTab widget) {
        Element li = DOM.createElement("li");
        widget.removeFromParent();
        getChildren().add(widget);
        li.appendChild(widget.getElement());
        getElement().appendChild(li);
        adopt(widget);
    }

    @Override
    public void addAndReplaceElement(Widget widget, Element toReplace) {
        if (widget instanceof ActionTab == false) {
            throw new IllegalArgumentException(
                    "TabBar can contain only action widgets");
        }
        ActionTab action = (ActionTab) widget;
        Element li = DOM.createElement("li");
        widget.removeFromParent();
        getChildren().add(widget);
        li.appendChild(widget.getElement());
        toReplace.getParentNode().replaceChild(li, toReplace);
        adopt(widget);
        if (action.isActive()) {
            setStyleName(li, "active");
        }
    }

    public ActionTab getActiveTab() {
        for (Widget w : getChildren()) {
            ActionTab action = (ActionTab) w;
            if (action.isActive()) {
                return action;
            }
        }
        return null;
    }

    public void onActivate(ActionTab action) {
        ActionTab active = getActiveTab();
        if (active != action) {
            setStyleName(active.getElement().getParentElement(), "active",
                    false);
            active.setActive(false);
            setStyleName(action.getElement().getParentElement(), "active");
            action.setActive(true);
        }
    }
}
